from django.db import models
from django.core.validators import FileExtensionValidator
from django.core.exceptions import ValidationError


STATUS_CHOICES = (('s', '启用'), ('f', '禁用'),)


# 自定义验证器

def validate_image_extension(value):
    ext = value.name.split('.')[-1]
    allowed_extensions = ['tar.gz']
    if ext not in allowed_extensions:
        raise ValidationError("文件格式不是tar.gz")

def validata_unique_soft_version(value):
    print(value,'valuename')
    flag = versioncontrol.objects.filter(soft_version=value)
    if flag:
        raise ValidationError('该版本已存在！！')


class versioncontrol(models.Model):
    soft_version = models.CharField(max_length=32, verbose_name="软件版本", validators=[validata_unique_soft_version])
    arm64 = models.FileField(verbose_name='arm64', upload_to='uploadss/', validators=[FileExtensionValidator(allowed_extensions=['gz'])],)
    amd64 = models.FileField(verbose_name='amd64', upload_to='uploadss/', validators=[FileExtensionValidator(allowed_extensions=['gz'])])
    stats = models.CharField(max_length=1, choices=STATUS_CHOICES, default='s', verbose_name="状态")

    # 设置主键
    def __str__(self):
        return self.soft_version



    # 用于给本表指定一个别名
    class Meta:
        verbose_name = "版本详情"
        # 下面这个变量是上面这个变量的复数形式
        verbose_name_plural = "version上传记录"
        db_table = 'versioncontrol'
        # icon = ''

    def save(self, *args, **kwargs):
        if self.arm64:
            print(self.arm64.name,'name')
            # 本地和linux服务器的路径显示不一样，复制到linux里需要进行修改，另外
            original_name1 = self.arm64.name.split('/')[-1]
            new_name1 = 'ansible_{}_arm64.tar.gz'.format(self.soft_version)
            self.arm64.name = self.arm64.name.replace(original_name1, new_name1)
        if self.amd64:
            original_name2 = self.amd64.name.split('/')[-1]
            new_name2 = 'ansible_{}_amd64.tar.gz'.format(self.soft_version)

            self.amd64.name = self.amd64.name.replace(original_name2, new_name2)
        super(versioncontrol, self).save(*args, **kwargs)